<template>
  <el-dialog
    v-model="visible"
    v-if="load"
    title="标签生成"
    width="650px"
    draggable
    @close="close"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :z-index="2000"
  >
    <el-form :model="formValues" ref="formRef" class="mx-5 my-5" label-width="100px">
      <el-form-item label="标签类型">
        <el-select
          v-model="formValues.label_type"
          placeholder="请选择"
          class="w-[100%]"
          multiple
          collapse-tags
          @change="changeLabelType"
        >
          <el-option
            :value="item.value"
            :label="item.label"
            v-for="item in labelTypeOptions"
            :key="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="平台、店铺"
        v-if="formValues.label_type.some((type) => [7, 11].includes(type))"
      >
        <SelectPlatformShop
          v-model:platform="formValues.platform"
          v-model:shop="formValues.shop"
        ></SelectPlatformShop>
      </el-form-item>
      <el-form-item
        label="生产批号"
        v-if="formValues.label_type.some((type) => [7, 8, , 11].includes(type))"
      >
        <el-input
          v-model="formValues.production_batch_no"
          placeholder="Production Batch No."
        ></el-input>
      </el-form-item>
      <el-form-item label="国家">
        <SelectCountry
          class="w-full"
          v-model="formValues.country"
          @change="changeName"
        ></SelectCountry>
        <el-checkbox v-model="formValues.is_combination">组合生成</el-checkbox>
      </el-form-item>
    </el-form>
    <div id="barcode" class="h-[110px]"></div>
    <div class="absolute bottom-[80px] left-0 w-full h-[110px] bg-[#ffff] z-10"></div>
    <template #footer>
      <div class="footer-btn">
        <el-button @click="close">取消</el-button>
        <el-button @click="createLabels('preview')" :loading="loading">预览</el-button>
        <el-button type="primary" :loading="loading" @click="createLabels('download-pdf')"
          >下载PDF</el-button
        >
        <el-button
          type="primary"
          :loading="loading"
          @click="createLabels('download-word')"
          >下载word</el-button
        >
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { labelTypeOptions } from "../data.js";
import SelectCountry from "@/components/SelectCountry";
import html2pdf from "html2pdf.js";
import { nextTick, reactive, toRefs } from "vue";
import { PDFDocument, StandardFonts } from "pdf-lib";
import { ElMessage } from "element-plus";
import { getSKUCustomList, getShopInfo, getSKUDetails } from "../api.js";
import SelectPlatformShop from "@/components/Selects/SelectPlatformShop";
import JSZip from "jszip";
import { getSupplierDetail } from "@/api/index.js";
import {
  image_list,
  image_name,
  tips,
  fixed_mark_map,
  tips_icon_map,
  brand_tips_icon_map,
  brandtips,
} from "../label_data.js";
import handleExportWord from "@/utils/xh-htmlword/index.js";
import JsBarcode from "jsbarcode";
import SelectBrand from "@/components/SelectBrand";

const formRef = ref();
const emit = defineEmits(["refresh"]);
const load = ref(false);

const data = reactive({
  visible: false,
  loading: false,
  formValues: {
    label_type: [],
    is_combination: false,
    platform: "",
    shop: "",
  },
  sku_list: [],
  country_list: [],
  label_list: [],
  companyInfo: null,
  sku_ids: [],
  htmlContent: "",
  skuDetails: [],
});

const {
  visible,
  loading,
  formValues,
  sku_list,
  country_list,
  label_list,
  companyInfo,
  sku_ids,
  htmlContent,
  skuDetails,
} = toRefs(data);

const open = async (ids) => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  sku_ids.value = ids;
  visible.value = true;
};

const getDetail = async () => {
  try {
    const res = await getSKUCustomList({
      sku_ids: sku_ids.value,
    });
    // 使用 map 处理每个元素，并等待所有 Promise 完成
    sku_list.value = await Promise.all(
      res.data.sku.map(async (item) => {
        if (item.goods_sku_supplier.length) {
          const supplier = item.goods_sku_supplier[0];
          if (!supplier.goods_sku_trade_agent || !supplier.goods_sku_trade_agent?.model) {
            supplier.goods_sku_trade_agent = supplier.goods_sku_trade_agent || {};
            // 获取模型名称
            let model;
            const specification_model = item.goods_spu.specification_model;
            if (item.goods_spu && !/[\u4e00-\u9fa5]/.test(specification_model)) {
              model = specification_model;
            } else {
              model = item.sku || item.custom_sku;
            }
            // 设置模型
            supplier.goods_sku_trade_agent.model = model;
          }

          if (
            !supplier.goods_sku_trade_agent ||
            !supplier.goods_sku_trade_agent?.supplier_name_en ||
            !supplier.goods_sku_trade_agent?.supplier_addr_en
          ) {
            const res = await getSupplierDetail({
              s_id: supplier.supplier_id,
            });
            const { basic } = res.data;
            supplier.goods_sku_trade_agent.supplier_name_en =
              supplier.goods_sku_trade_agent.supplier_name_en || basic.supplier_en_name;
            supplier.goods_sku_trade_agent.supplier_addr_province =
              supplier.goods_sku_trade_agent.supplier_addr_province ||
              basic.province_en_name;
            supplier.goods_sku_trade_agent.supplier_addr_city =
              supplier.goods_sku_trade_agent.supplier_addr_city || basic.city_en_name;
            supplier.goods_sku_trade_agent.supplier_addr_area =
              supplier.goods_sku_trade_agent.supplier_addr_area || basic.district_en_name;
            supplier.goods_sku_trade_agent.supplier_addr_en =
              supplier.goods_sku_trade_agent.supplier_addr_en || basic.english_address;
          }
        }

        return item;
      })
    );
    country_list.value = res.data.country;
  } catch (e) {
    throw Error(e);
  }
};

const close = async (refresh) => {
  formValues.value = {
    label_type: [],
    is_combination: false,
  };
  await nextTick();
  formRef.value.resetFields();
  if (refresh) emit("refresh");
  loading.value = false;
  visible.value = false;
};

defineExpose({ open });

const changeLabelType = (val) => {
  if (!val.includes(7)) {
    formValues.value.platform = "";
    formValues.value.shop = "";
  }
};

const changeName = (val) => {
  formValues.value.country_name = val;
};

// 初始化处理
const createLabels = async (type) => {
  if (!formValues.value.label_type.length) {
    ElMessage.error("请选择标签类型");
    return;
  }

  if ([1, 7, 8].includes(formValues.value.label_type) && !formValues.value.country) {
    ElMessage.error("欧英代标签需通过国家选择进口公司，请选择");
    return;
  }
  loading.value = true;

  if (formValues.value.label_type.some((label) => [1, 7].includes(label))) {
    if (!formValues.value.platform && !formValues.value.shop) {
      ElMessage.error("欧英代标签需通过平台、店铺获取信息，请选择");
      loading.value = false;
      return;
    }
    const res = await getShopInfo({
      shop_id: formValues.value.shop,
    });
    companyInfo.value = {
      company_name_py: res.data?.company_name_py || "",
      company_address_pinyin: res.data?.company_address_pinyin || "",
      email: res.data.email,
    };
  }

  if (formValues.value.label_type.some((label) => [10].includes(label))) {
    const res = await getSKUDetails({
      id: sku_ids.value,
    });
    skuDetails.value = res.data;
  }

  await getDetail();

  setTimeout(() => {
    const list = [];
    const is_Ouyingdai = formValues.value.label_type.some((element) =>
      [1, 7, 8, 11].includes(element)
    );
    const is_only_Ouyingdai = formValues.value.label_type.every((element) =>
      [1, 7, 8, 11].includes(element)
    );
    const isUK = formValues.value.country == 5 || formValues.value.country === 264;

    const filter_label = formValues.value.label_type.filter((i) => {
      return [1, 7, 8, 11].includes(i);
    });

    if (formValues.value.is_combination) {
      sku_list.value.forEach((i) => {
        const base_image = []; // 基础版
        const gprs_image = []; // GPSR版

        if (is_Ouyingdai) {
          // 一级分类=海外仓汽摩配类、亚马逊汽配,汽摩配，则默认
          // 一级分类=海外仓家居类、海外仓运动与健康类，则默认
          const category = i.goods_spu?.spu_category[0] ?? -1;
          let manufacturer_email = "";
          if ([196, 24, 701].includes(category)) {
            manufacturer_email = "Isinmotor@sz2k.com";
          } else if ([148, 224].includes(category)) {
            manufacturer_email = "oyajia-homecs@outlook.com";
          }

          base_image.push(getImageData(7));
          gprs_image.push(getImageData(7));
          gprs_image.push(getImageData(2));

          if (is_only_Ouyingdai) {
            // 是否只有欧英代
            if (i.goods_sku_authentication?.length) {
              i.goods_sku_authentication.forEach((i) => {
                if (
                  i.authentication_name == "CE" &&
                  i.country.some((j) => {
                    const isMatch = j.country_id == formValues.value.country;
                    const isSpecialCase =
                      [5, 264].includes(j.country_id) &&
                      [5, 264].includes(formValues.value.country);
                    return isMatch || isSpecialCase;
                  })
                ) {
                  base_image.push(getImageData(2));
                  gprs_image.push(getImageData(2));
                } else if (
                  i.authentication_name == "UKCA" &&
                  i.country.some((j) => {
                    const isMatch = j.country_id == formValues.value.country;
                    const isSpecialCase =
                      [5, 264].includes(j.country_id) &&
                      [5, 264].includes(formValues.value.country);
                    return isMatch || isSpecialCase;
                  })
                ) {
                  base_image.push(getImageData(6));
                }
              });
            }

            gprs_image.push(getImageData(5));
            const regex = new RegExp(["带电", "电池", "移动电源", "电子烟"].join("|"));

            if (regex.test(i.goods_spu.logistics_attributes_name)) {
              base_image.push(getImageData(3));
              gprs_image.push(getImageData(3));
            }
          } else {
            formValues.value.label_type.forEach((j) => {
              if (j == 2) {
                base_image.push(getImageData(2));
                gprs_image.push(getImageData(2));
              } else if (j == 3) {
                base_image.push(getImageData(3));
                gprs_image.push(getImageData(3));
              } else if (j == 4) {
                const image = [];
                const find_tag_style = i.goods_sku_supplier[0]?.goods_sku_identification_processing.find(
                  (i) => i.product_identification == 3
                );
                if (find_tag_style?.tag_style > 1) {
                  image.push(getImageData(`4-${find_tag_style?.tag_style}`));
                } else {
                  image.push(getImageData(7));
                }
                list.push({
                  image,
                });
              } else if (j == 5) {
                base_image.push(getImageData(5));
                gprs_image.push(getImageData(5));
              } else if (j == 6) {
                base_image.push(getImageData(6));
                gprs_image.push(getImageData(6));
              } else if (j == 10) {
                const findItem = skuDetails.value.find((j) => i.sku == j.sku);
                if (findItem == undefined) return;
                if (findItem?.goods_sku_sales_info.ean_number) {
                  list.push({
                    ean_number: findItem?.goods_sku_sales_info.ean_number,
                    specification_model: findItem?.goods_spu.specification_model,
                    sku: i.sku,
                    type: 10,
                  });
                } else {
                  ElMessage.error("EAN码未填写，请先填写EAN码");
                }
              }
            });
          }
          const product_name =
            i.goods_sku_supplier[0]?.goods_sku_trade_agent?.product_name ||
            i.goods_sku_supplier[0]?.goods_sku_customs?.en_name;

          const unique_base_image = [...new Set(base_image)];
          const unique_gprs_image = [...new Set(gprs_image)];

          const packaging_image = [];
          const find_tag_style = i.goods_sku_supplier[0]?.goods_sku_identification_processing.find(
            (i) => i.product_identification == 3
          );
          if (find_tag_style?.tag_style > 1) {
            packaging_image.push(getImageData(`4-${find_tag_style?.tag_style}`));
          } else {
            packaging_image.push(getImageData(7));
          }
          // 非英国增加2个标签
          if (!isUK) {
            packaging_image.push(getImageData(8));
            packaging_image.push(getImageData(9));
          }

          filter_label.forEach((j) => {
            let find;
            if (j == 11) {
              find = country_list.value.find(
                (k) =>
                  k.base_trade_agent_country.some(
                    (item) => item.country_id === formValues.value.country
                  ) &&
                  k.platform_id == formValues.value.platform &&
                  k.shop_ids.includes(formValues.value.shop) &&
                  k.brand_ids.includes(i.goods_sku_sales_info?.brand_id)
              );
            } else if (j == 7) {
              find = country_list.value.find(
                (k) =>
                  k.base_trade_agent_country.some(
                    (item) => item.country_id === formValues.value.country
                  ) &&
                  k.platform_id == formValues.value.platform &&
                  k.shop_ids.includes(formValues.value.shop) &&
                  !k.brand_ids?.length
              );
            } else {
              find = country_list.value.find(
                (k) =>
                  k.base_trade_agent_country.some(
                    (item) => item.country_id === formValues.value.country
                  ) &&
                  !k.platform_id &&
                  !k.shop_ids?.length &&
                  !k.brand_ids?.length
              );
            }

            list.push({
              base_importer: find?.base_importer || {}, // 欧英代公司维护信息
              goods_sku_trade_agent: i.goods_sku_supplier[0]?.goods_sku_trade_agent, // 默认供应商欧英代产品信息
              image: j == 1 ? unique_base_image : unique_gprs_image, // 根据判断生成需要打印的标签
              sku: i.sku || i.custom_sku, // 当前SKU 自定义SKU
              supplier_name: i.goods_sku_supplier[0]?.supplier_name, // 供应商名称
              country_name: formValues.value.country_name, // 国家名称
              type: j, // 类型
              tips, // GPSR 固定提示信息
              fixed_mark: isUK ? fixed_mark_map.get(8) : fixed_mark_map.get(7), // GPSR 固定图案 区分英国跟其他国家
              product_name, // 产品名称
              production_batch_no: formValues.value.production_batch_no || "", // 产品批次号
              manufacturer_email, // 邮箱
              companyInfo: companyInfo.value, // 通过店铺获取到  店铺信息
              tips_text: isUK
                ? "Warning: Please keep away from fire, children and pets!"
                : "Achtung: Bitte von Feuer, Kindern und Haustieren fernhalten!",
              address_tip: isUK ? "Address" : "Handelsregister", // 固定提示信息 区分英国跟其他国家
              telephone_tip: isUK ? "Telephone number" : "Telefonnummer", // 固定提示信息 区分英国跟其他国家
              packaging_image, // 包装法图片 根据产品标识维护样式
              brandtips,
              brand_name: i?.goods_sku_sales_info.brand_name,
            });
          });
        } else if (
          formValues.value.label_type.includes(3) &&
          formValues.value.label_type.includes(5)
        ) {
          // 只选择电池法和WEEE，默认带有循环标。
          image.push(getImageData(7));
          image.push(getImageData(3));
          image.push(getImageData(5));
          list.push({
            is_Ouyingdai: false,
            image,
            type: 8,
          });
        } else if (formValues.value.label_type.includes(5)) {
          image.push(getImageData(7));
          image.push(getImageData(5));
          list.push({
            is_Ouyingdai: false,
            image,
            type: 9,
          });
        } else {
          formValues.value.label_type.forEach((j) => {
            if (j == 10) {
              const findItem = skuDetails.value.find((j) => i.sku == j.sku);
              if (findItem == undefined) return;
              if (findItem?.goods_sku_sales_info.ean_number) {
                list.push({
                  ean_number: findItem?.goods_sku_sales_info.ean_number,
                  specification_model: findItem?.goods_spu.specification_model,
                  sku: i.sku,

                  type: 10,
                });
              } else {
                ElMessage.error("EAN码未填写，请先填写EAN码");
              }
            } else {
              const image = [];
              if (j == 4) {
                const find_tag_style = i.goods_sku_supplier[0]?.goods_sku_identification_processing.find(
                  (i) => i.product_identification == 3
                );
                if (find_tag_style?.tag_style > 1) {
                  image.push(getImageData(`4-${find_tag_style?.tag_style}`));
                } else {
                  image.push(getImageData(7));
                }
              } else {
                image.push(getImageData(j));
              }
              list.push({
                is_Ouyingdai: false,
                image,
              });
            }
          });
        }
      });

      label_list.value = list;
      nextTick(() => {
        if (type == "preview") {
          previewAll();
        } else if (type == "download-pdf") {
          downloadPDFAll();
        } else if (type == "download-word") {
          downloadWordAll();
        }
      });
    } else {
      sku_list.value.forEach((i) => {
        const product_name =
          i.goods_sku_supplier[0]?.goods_sku_trade_agent?.product_name ||
          i.goods_sku_supplier[0]?.goods_sku_customs?.en_name;

        formValues.value.label_type.forEach((j) => {
          let find;
          if (j == 11) {
            find = country_list.value.find(
              (k) =>
                k.base_trade_agent_country.some(
                  (item) => item.country_id === formValues.value.country
                ) &&
                k.platform_id == formValues.value.platform &&
                k.shop_ids.includes(formValues.value.shop) &&
                k.brand_ids.includes(i.goods_sku_sales_info?.brand_id)
            );
          } else if (j == 7) {
            find = country_list.value.find(
              (k) =>
                k.base_trade_agent_country.some(
                  (item) => item.country_id === formValues.value.country
                ) &&
                k.platform_id == formValues.value.platform &&
                k.shop_ids.includes(formValues.value.shop) &&
                !k.brand_ids?.length
            );
          } else {
            find = country_list.value.find(
              (k) =>
                k.base_trade_agent_country.some(
                  (item) => item.country_id === formValues.value.country
                ) &&
                !k.platform_id &&
                !k.shop_ids?.length &&
                !k.brand_ids?.length
            );
          }
          if (j == 1) {
            const image = [];
            image.push(getImageData(7));
            list.push({
              base_importer: find?.base_importer || {},
              goods_sku_trade_agent: i.goods_sku_supplier[0]?.goods_sku_trade_agent,
              image,
              sku: i.sku || i.custom_sku,
              supplier_name: i.goods_sku_supplier[0]?.supplier_name,
              country_name: formValues.value.country_name,
              product_name,
              type: j,
            });
          } else if (j == 7) {
            const image = [];
            image.push(getImageData(7));
            const find_tag_style = i.goods_sku_supplier[0]?.goods_sku_identification_processing.find(
              (i) => i.product_identification == 3
            );
            const packaging_image = [];
            if (find_tag_style?.tag_style > 1) {
              packaging_image.push(getImageData(`4-${find_tag_style?.tag_style}`));
            } else {
              packaging_image.push(getImageData(7));
            }
            if (!isUK) {
              packaging_image.push(getImageData(8));
              packaging_image.push(getImageData(9));
            }
            list.push({
              base_importer: find?.base_importer || {},
              goods_sku_trade_agent: i.goods_sku_supplier[0]?.goods_sku_trade_agent,
              image,
              sku: i.sku || i.custom_sku,
              supplier_name: i.goods_sku_supplier[0]?.supplier_name,
              country_name: formValues.value.country_name,
              production_batch_no: formValues.value.production_batch_no,
              product_name,
              companyInfo: companyInfo.value,
              tips,
              fixed_mark: isUK ? fixed_mark_map.get(8) : fixed_mark_map.get(7),
              type: j,
              address_tip: isUK ? "Address" : "Handelsregister",
              telephone_tip: isUK ? "Telephone number" : "Telefonnummer", // 固定提示信息 区分英国跟其他国家
              packaging_image, // 包装法图片 根据产品标识维护样式
            });
          } else if (j == 8) {
            const image = [];
            image.push(getImageData(7));
            image.push(getImageData(2));
            image.push(getImageData(5));

            // 一级分类=海外仓汽摩配类、亚马逊汽配，则默认
            // 一级分类=海外仓家居类、海外仓运动与健康类，则默认
            const category = i.goods_spu?.spu_category[0] ?? -1;
            let manufacturer_email = "";
            if ([196, 24, 701].includes(category)) {
              manufacturer_email = "Isinmotor@sz2k.com";
            } else if ([148, 224].includes(category)) {
              manufacturer_email = "oyajia-homecs@outlook.com";
            }

            list.push({
              base_importer: find?.base_importer || {},
              goods_sku_trade_agent: i.goods_sku_supplier[0]?.goods_sku_trade_agent,
              image,
              sku: i.sku || i.custom_sku,
              supplier_name: i.goods_sku_supplier[0]?.supplier_name,
              country_name: formValues.value.country_name,
              type: j,
              production_batch_no: formValues.value.production_batch_no,
              product_name,
              manufacturer_email,
              tips_text: isUK
                ? "Warning: Please keep away from fire, children and pets!"
                : "Achtung: Bitte von Feuer, Kindern und Haustieren fernhalten!",
              fixed_mark: isUK ? fixed_mark_map.get(8) : fixed_mark_map.get(7),
              address_tip: isUK ? "Address" : "Handelsregister",
              telephone_tip: isUK ? "Telephone number" : "Telefonnummer", // 固定提示信息 区分英国跟其他国家
            });
          } else if (j == 10) {
            const findItem = skuDetails.value.find((j) => i.sku == j.sku);
            if (findItem == undefined) return;
            if (findItem?.goods_sku_sales_info.ean_number) {
              list.push({
                ean_number: findItem?.goods_sku_sales_info.ean_number,
                specification_model: findItem?.goods_spu.specification_model,
                sku: i.sku,
                type: j,
              });
            } else {
              ElMessage.error("EAN码未填写，请先填写EAN码");
            }
          } else if (j == 11) {
            const image = [];
            image.push(getImageData(7));
            image.push(getImageData(2));
            image.push(getImageData(5));

            // 一级分类=海外仓汽摩配类、亚马逊汽配，则默认
            // 一级分类=海外仓家居类、海外仓运动与健康类，则默认
            const category = i.goods_spu?.spu_category[0] ?? -1;
            let manufacturer_email = "";
            if ([196, 24, 701].includes(category)) {
              manufacturer_email = "Isinmotor@sz2k.com";
            } else if ([148, 224].includes(category)) {
              manufacturer_email = "oyajia-homecs@outlook.com";
            }

            list.push({
              base_importer: find?.base_importer || {},
              goods_sku_trade_agent: i.goods_sku_supplier[0]?.goods_sku_trade_agent,
              image,
              sku: i.sku || i.custom_sku,
              supplier_name: i.goods_sku_supplier[0]?.supplier_name,
              country_name: formValues.value.country_name,
              type: j,
              production_batch_no: formValues.value.production_batch_no,
              product_name,
              manufacturer_email,
              tips_text: isUK
                ? "Warning: Please keep away from fire, children and pets!"
                : "Achtung: Bitte von Feuer, Kindern und Haustieren fernhalten!",
              fixed_mark: isUK ? fixed_mark_map.get(8) : fixed_mark_map.get(7),
              address_tip: isUK ? "Address" : "Handelsregister",
              telephone_tip: isUK ? "Telephone number" : "Telefonnummer", // 固定提示信息 区分英国跟其他国家
              brandtips,
              brand_name: i?.goods_sku_sales_info.brand_name,
            });
          } else {
            const image = [];
            if (j == 4) {
              const find_tag_style = i.goods_sku_supplier[0]?.goods_sku_identification_processing.find(
                (i) => i.product_identification == 3
              );
              if (find_tag_style?.tag_style > 1) {
                image.push(getImageData(`4-${find_tag_style?.tag_style}`));
              } else {
                image.push(getImageData(7));
              }
              list.push({
                image,
                type: j,
              });
            } else {
              image.push(getImageData(j));
              list.push({
                image,
                type: j,
              });
            }
          }
        });
      });

      label_list.value = list;
      nextTick(() => {
        if (type == "preview") {
          previewAll();
        } else if (type == "download-pdf") {
          downloadPDFAll();
        } else if (type == "download-word") {
          downloadWordAll();
        }
      });
    }
  }, 0);
};

// 处理欧英代HTML
const generateEuropeanStandardLabelHtml = (item, create_type = "pdf") => {
  return `<table border="1" cellpadding="6" style="font-size: 12px; border-collapse: collapse;border: 1px solid black;font-family: 'Cambria'"
    >
      <tbody>
      <tr style="border-bottom: 1px solid black;width: 355px;">
        <td>
          <div style="margin-top: -10px">Product name：${item.product_name}</div>
          <div>
            Lot number/model/serial number：${
              item.goods_sku_trade_agent?.lot_number
                ? item.goods_sku_trade_agent?.lot_number
                : ""
            }
            ${
              item.goods_sku_trade_agent?.lot_number && item.goods_sku_trade_agent?.model
                ? "/"
                : ""
            }
            ${item.goods_sku_trade_agent?.model ? item.goods_sku_trade_agent?.model : ""}
            ${
              item.goods_sku_trade_agent?.model &&
              item.goods_sku_trade_agent?.serial_number
                ? "/"
                : ""
            }
            ${
              item.goods_sku_trade_agent?.serial_number
                ? item.goods_sku_trade_agent?.serial_number
                : ""
            }
          </div>
          <div>
            Working voltage/applicable age：${
              item.goods_sku_trade_agent?.working_voltage
                ? item.goods_sku_trade_agent?.working_voltage
                : ""
            }
            ${
              item.goods_sku_trade_agent?.working_voltage &&
              item.goods_sku_trade_agent?.applicable_age
                ? "/"
                : ""
            }
            ${
              item.goods_sku_trade_agent?.applicable_age
                ? item.goods_sku_trade_agent?.applicable_age
                : ""
            }
          </div>
        </td>
      </tr>
      <tr style="border-bottom: 1px solid black;;width: 355px;">
        <td>
          <div style="margin-top: -10px">Manufacturer：${
            item.goods_sku_trade_agent?.supplier_name_en || ""
          }</div>
          <div>Address：${item.goods_sku_trade_agent?.supplier_addr_en || ""}</div>
          <div>Warning：Please keep away from fire, children and pets!</div>
        </td>
      </tr>
      <tr style="border-bottom: 1px solid black;;width: 355px;">
        <td>
          <div style="margin-top: -10px">Importer：${
            item.base_importer?.importer_company_name || ""
          }</div>
          <div>Address：${item.base_importer?.province || ""}${
    item.base_importer?.city || ""
  }${item.base_importer?.arae || ""} ${item.base_importer?.address || ""}</div>
          <div>Email：${item.base_importer?.email || ""}</div>
          <div>
            Telephone number：${
              item.base_importer?.is_print_telephone == 1
                ? item.base_importer?.telephone
                : ""
            }
          </div>
        </td>
      </tr>
      <tr>
        <td>
          <div style="display: flex; width: 355px;">
          ${item.image
            .map(
              (i) =>
                `<span style="margin-right: 8px;"><img width="${i.width}" height="${
                  i.height
                }"  src="${i.src}" />${create_type == "word" ? "&nbsp" : ""} </span>`
            )
            .join("")}
            </div>
        </td>
      </tr>
      </tbody>
    </table>`;
};

// 处理 欧英代（GPSR）家居&汽配&智能清洁
const generateGPSREuropeanStandardLabelHtml = (item, create_type = "pdf") => {
  return `<table border="1" cellpadding="6" style="font-size: 11px; border-collapse: collapse;border: 1px solid black;font-family: 'Cambria'"
    >
      <tbody>
      <tr style="border-bottom: 1px solid black;">
        <td colspan="2">
          <div style="margin-top: -10px">Product name: ${item.product_name || ""}</div>
          <div>Production Batch No.: ${item.production_batch_no || ""}</div>
          <div><span style="min-width:120px;display: inline-block">Model: ${
            item.goods_sku_trade_agent?.model || ""
          }</span> <span style="margin-left:12px">Operating Voltage: ${
    item.goods_sku_trade_agent?.working_voltage || ""
  }</span></div>
          <div>Manufacturer: ${item.goods_sku_trade_agent?.supplier_name_en || ""}</div>
          <div style="word-break: break-all;">Manufacturer Address:  ${
            item.goods_sku_trade_agent?.supplier_addr_province || ""
          } ${item.goods_sku_trade_agent?.supplier_addr_city || ""} ${
    item.goods_sku_trade_agent?.supplier_addr_area || ""
  }${item.goods_sku_trade_agent?.supplier_addr_en || ""}</div>
          <div>Manufacturer Email:${item.manufacturer_email}</div>
          <div>${item.tips_text}</div>
          <div>Made in china</div>
        </td>
        </tr>
        <tr style="border-bottom: 1px solid black;">
          <td colspan="2">
            <div style="padding: 0px;display: flex;">
            ${item.image
              .map(
                (i) =>
                  `<span style="margin-right: 8px;"><img width="${
                    i.width * 0.8
                  }" height="${i.height * 0.8}"  src="${i.src}" />${
                    create_type == "word" ? "&nbsp" : ""
                  }</span>`
              )
              .join("")}
            </div>
          </td>
        </tr>
        <tr style="border-bottom: 1px solid black;">
          <td style="${create_type == "pdf" ? "width: 80px" : ""}">
              <img style="width: 80px;height:56px" width="80" height="56"  src="${
                item.fixed_mark
              }" />
          </td>
          <td>
            <div style="margin-top: -10px">Importer:${
              item.base_importer?.importer_company_name || ""
            }</div>
            <div>${item.address_tip}:${item.base_importer?.address || ""}</div>
            <div>Email:${item.base_importer?.email || ""}</div>
            <div>${item.telephone_tip}:${
    item.base_importer?.is_print_telephone == 1 ? item.base_importer?.telephone : ""
  }</div>
          </td>
        </tr>
        </tbody>
    </table>`;
};

// GPSR（欧洲）标签
const generateGPSREuropeanLabelHtml = (item, create_type = "pdf") => {
  return `<table border="1" cellpadding="6" style="font-size: 12px; border-collapse: collapse;border: 1px solid black;font-family: 'Cambria'"
    >
      <tbody>
      <tr style="border-bottom: 1px solid black;width: 355px;">
        <td  colspan="2">
          <div style="margin-top: -10px">Product name: ${item.product_name}</div>
          <div>Production Batch No.: ${item.production_batch_no || ""}</div>
          <div>Manufacture: ${item.companyInfo?.company_name_py}</div>
          <div style="word-break: break-all;">Manufacture Address: ${
            item.companyInfo?.company_address_pinyin
          }</div>
          <div>Manufacture Email: ${item.companyInfo?.email}</div>
          </td>
        </tr>
      <tr style="border-bottom: 1px solid black;width: 355px;">
        <td colspan="2">
          ${item.tips
            .map(
              (i, index) =>
                `<div style="display: flex;height:18px;line-height: 8px;margin-bottom: 2px;font-size: 10px;font-family:Microsoft YaHei;"><img width="20" height="18" style="margin-right: 3px" src="${getTipIcon(
                  index
                )}"> <img width="20" height="18" src="https://xc-goods.oss-cn-shenzhen.aliyuncs.com/20240909/data/Company/%2820240909-103256%29%2B103317410af0f6b15559c85580ec104a74eaae15e.jpg"> <span style="margin-left: 5px">${
                  i.text
                }</span></div>`
            )
            .join("")}
          </td>
        </tr>
      <tr style="border-bottom: 1px solid black;width: 355px;">
        <td  colspan="2">
          <div style="display: flex;">
          ${item.packaging_image
            .map(
              (i) =>
                `<span style="margin-right: 8px;"><img width="${i.width}" height="${
                  i.height
                }"  src="${i.src}" />${create_type == "word" ? "&nbsp" : ""}</span>`
            )
            .join("")}
          </div>
          </td>
        </tr>
        <tr style="border-bottom: 1px solid black;width: 355px;">
          <td style="${create_type == "pdf" ? "width: 100px" : ""}">
            <img style="width: 100px;height:70px" width="100" height="79" src="${
              item.fixed_mark
            }" />
          </td>
          <td>
            <div style="margin-top: -10px">${
              item.base_importer?.importer_company_name || ""
            }</div>
              <div style="word-break: break-all;">${item.address_tip}: ${
    item.base_importer?.address || ""
  }</div>
              <div>Email: ${item.base_importer?.email || ""}</div>
          </td>
        </tr>
      </tbody>
    </table>`;
};

const generateLabelHtml = (item) => {
  return `<div style="font-size: 14px;"
    >
      <div style="padding: 8px;display: flex;justify-content: center;width: 355px;">
        ${item.image.map(
          (i) =>
            `<div style="margin-right: 8px;"><img width="${i.width}" height="${i.height}"  src="${i.src}" /></div>`
        )}
        </div>
  </div`;
};

// 生成欧英代（GPSR）品牌
const generateGPSRBrandLabelHtml = (item, create_type = "pdf") => {
  return `<table border="1" cellpadding="6" style="font-size: 10px; border-collapse: collapse;border: 1px solid black;font-family: 'Cambria'"
    >
      <tbody>
      <tr style="border-bottom: 1px solid black;">
        <td  colspan="2">
          <div style="margin-top: -10px">Product name: ${item.product_name}</div>
          <div>Model: ${item.goods_sku_trade_agent?.model}</div>
          <div>Manufacturer: ${item.goods_sku_trade_agent?.supplier_name_en || ""}</div>
          <div style="word-break: break-all;">Manufacturer Address:  ${
            item.goods_sku_trade_agent?.supplier_addr_province || ""
          }${item.goods_sku_trade_agent?.supplier_addr_city || ""} ${
    item.goods_sku_trade_agent?.supplier_addr_area || ""
  }${item.goods_sku_trade_agent?.supplier_addr_en || ""}</div>
          <div>Manufacture Email: support@kaitolhome.com</div>
          </td>
        </tr>
      <tr style="border-bottom: 1px solid black;">
        <td colspan="2">
          ${item.brandtips
            .map(
              (i, index) =>
                `<div style="margin-bottom: 2px;font-size: 10px;font-family:Microsoft YaHei;word-wrap: break-word;white-space: normal;"><img width="16" height="16" style="margin-right: 3px;display: inline-block;margin-top:4px" src="${getBrandTipIcon(
                  index
                )}"> <img style="display: inline-block;margin-top:4px" width="16" height="16" src="https://xc-goods.oss-cn-shenzhen.aliyuncs.com/20240909/data/Company/%2820240909-103256%29%2B103317410af0f6b15559c85580ec104a74eaae15e.jpg"> <span style="line-height:-8px;font-size: 8px;"> ${
                  i.text
                }</span></div>`
            )
            .join("")}
          </td>
        </tr>
        <tr style="border-bottom: 1px solid black;">
          <td style="${create_type == "pdf" ? "width: 100px" : ""}">
            <img style="width: 100px;height:70px" width="100" height="79" src="${
              item.fixed_mark
            }" />
          </td>
          <td>
            <div style="margin-top: -10px">${
              item.base_importer?.importer_company_name || ""
            }</div>
              <div style="word-break: break-all;">${item.address_tip}:${
    item.base_importer?.address || ""
  }</div>
              <div>Email: ${item.base_importer?.email || ""} </div>
              <div>${item.telephone_tip}:${
    item.base_importer?.is_print_telephone == 1 ? item.base_importer?.telephone : ""
  }</div>

          </td>
        </tr>
        <tr style="border-bottom: 1px solid black;">
          <td>
                     <div style="display: flex;">
          ${item.image
            .map(
              (i) =>
                `<span style="margin-right: 8px;"><img width="${i.width}" height="${
                  i.height
                }"  src="${i.src}" />${create_type == "word" ? "&nbsp" : ""}</span>`
            )
            .join("")}
          </div>
          </td>
          <td>
            <div style="margin-top: -10px"></div>
              <div>Country Oringin: Made In China</div>
              <div>Brand: ${item.brand_name}</div>
              <div>Product batch number: ${item.production_batch_no}</div>
          </td>
        </tr>
      </tbody>
    </table>`;
};
// 批量预览
const previewAll = async () => {
  try {
    const promises = [];
    if (label_list.value.length == 0) {
      loading.value = false;
      return;
    }
    for (let index = 0; index < label_list.value.length; index++) {
      let element;
      if (label_list.value[index].type == 1) {
        element = generateEuropeanStandardLabelHtml(label_list.value[index]);
      } else if (label_list.value[index].type == 7) {
        element = generateGPSREuropeanLabelHtml(label_list.value[index]);
      } else if (label_list.value[index].type == 8) {
        element = generateGPSREuropeanStandardLabelHtml(label_list.value[index]);
      } else if (label_list.value[index].type == 10) {
        element = createCode(label_list.value[index]);
        if (element === null) {
          ElMessage.error(
            `SKU: ${label_list.value[index].sku}, 生成 EAN 码失败，请检查 EAN 码是否正确`
          );
          loading.value = false;
          return;
        }
      } else if (label_list.value[index].type == 11) {
        element = generateGPSRBrandLabelHtml(label_list.value[index]);
      } else {
        element = generateLabelHtml(label_list.value[index]);
      }
      promises.push(preview(element, index, label_list.value[index].type));
    }
    // 等待所有 promise 解析
    const pdfContents = await Promise.all(promises);
    // 创建一个空白的 PDF 文档
    const mergedPdf = await PDFDocument.create();
    // 合并所有 PDF 内容到一个单独的 PDF 文档中
    for (const pdfContent of pdfContents) {
      const pdfDoc = await PDFDocument.load(pdfContent);
      const copiedPages = await mergedPdf.copyPages(pdfDoc, pdfDoc.getPageIndices());
      copiedPages.forEach((page) => {
        mergedPdf.addPage(page);
      });
    }
    // 将合并后的 PDF 导出为 Blob 对象
    const pdfBytes = await mergedPdf.save();
    // 创建合并后的 PDF 的 URL
    const pdfURL = URL.createObjectURL(new Blob([pdfBytes], { type: "application/pdf" }));
    // 在新窗口中打开合并后的 PDF
    window.open(pdfURL, "_blank");
    loading.value = false;
  } catch (error) {
    loading.value = false;
    console.error("预览项目时出错:", error);
  }
};

// 批量下载PDF
const downloadPDFAll = async () => {
  const zip = new JSZip(); // 创建一个新的 Zip 实例
  for (let index = 0; index < label_list.value.length; index++) {
    let element;
    if (label_list.value[index].type == 1) {
      element = generateEuropeanStandardLabelHtml(label_list.value[index]);
    } else if (label_list.value[index].type == 7) {
      element = generateGPSREuropeanLabelHtml(label_list.value[index]);
    } else if (label_list.value[index].type == 8) {
      element = generateGPSREuropeanStandardLabelHtml(label_list.value[index]);
    } else if (label_list.value[index].type == 10) {
      element = createCode(label_list.value[index]);
      if (element === null) {
        ElMessage.error(
          `SKU: ${label_list.value[index].sku}, 生成 EAN 码失败，请检查 EAN 码是否正确`
        );
        loading.value = false;
        return;
      }
    } else if (label_list.value[index].type == 11) {
      element = generateGPSRBrandLabelHtml(label_list.value[index]);
    } else {
      element = generateLabelHtml(label_list.value[index]);
    }
    await downloadPDF(element, index, label_list.value[index], zip);
  }
  zip.generateAsync({ type: "blob" }).then(function (content) {
    saveAs(content, "标签生成.zip");
  });
};

// 批量下载Word
const downloadWordAll = async () => {
  const zip = new JSZip(); // 创建一个新的 Zip 实例
  for (let index = 0; index < label_list.value.length; index++) {
    let element;
    if (label_list.value[index].type == 1) {
      element = generateEuropeanStandardLabelHtml(label_list.value[index], "word");
    } else if (label_list.value[index].type == 7) {
      element = generateGPSREuropeanLabelHtml(label_list.value[index], "word");
    } else if (label_list.value[index].type == 8) {
      element = generateGPSREuropeanStandardLabelHtml(label_list.value[index], "word");
    } else if (label_list.value[index].type == 10) {
      element = createCode(label_list.value[index]);
      if (element === null) {
        ElMessage.error(
          `SKU: ${label_list.value[index].sku}, 生成 EAN 码失败，请检查 EAN 码是否正确`
        );
        loading.value = false;
        return;
      }
    } else if (label_list.value[index].type == 11) {
      element = generateGPSRBrandLabelHtml(label_list.value[index]);
    } else {
      element = generateLabelHtml(label_list.value[index]);
    }
    await downloadWord(element, index, label_list.value[index], zip);
  }
  zip.generateAsync({ type: "blob" }).then(function (content) {
    saveAs(content, "标签生成.zip");
  });
};

const preview = (element, index, type) => {
  return new Promise((resolve, reject) => {
    const opt = {
      margin: [1, 7, 8, 11].includes(type) ? 1 : 0,
      filename: "myfile.pdf",
      image: { type: "jpeg", quality: 1 },
      html2canvas: { scale: 10, useCORS: true },
      jsPDF: {
        unit: "mm",
        format: getPDFSize(type),
        orientation: [1, 7, 8, 11].includes(type) ? "portrait" : "landscape",
      },
    };

    const instance = html2pdf().from(element).set(opt).output("blob");
    instance
      .then((blob) => {
        const reader = new FileReader();
        reader.onload = () => {
          const arrayBuffer = reader.result;
          const uint8Array = new Uint8Array(arrayBuffer);
          resolve(uint8Array);
        };
        reader.onerror = (error) => {
          console.error("Error reading PDF blob:", error);
          reject(error);
        };
        reader.readAsArrayBuffer(blob);
      })
      .catch((error) => {
        console.error("Error generating PDF:", error);
        reject(error);
      });
  });
};

const downloadPDF = async (element, index, row, zip) => {
  let filename = "";
  if ([1, 7, 8, 11].includes(row.type)) {
    filename = `${row.sku}-${row.supplier_name}-${row.country_name}${index + 1}`;
  } else {
    filename = image_name.get(row.type);
  }
  const opt = {
    margin: [1, 7, 8].includes(row.type) ? 1 : 0,
    filename,
    image: { type: "jpeg", quality: 1 },
    html2canvas: { scale: 10, useCORS: true },
    jsPDF: {
      unit: "mm",
      format: getPDFSize(row.type),
      orientation: [1, 7, 8].includes(row.type) ? "portrait" : "landscape",
    },
  };
  // 使用 html2pdf 生成图片并添加到全局 zip 实例中
  const canvas = html2pdf().from(element).set(opt).output("blob");
  zip.file(`${filename}.pdf`, canvas);
  loading.value = false;
};

const downloadWord = async (element, index, row, zip) => {
  console.log("row.sku");
  console.log(row.sku);

  let filename = "";
  if ([1, 7, 8, 11].includes(row.type)) {
    filename = `${row.sku}-${row.supplier_name}-${row.country_name}${index + 1}`;
  } else {
    filename = image_name.get(row.type);
  }
  const elementDom = await stringToDom(element);
  return new Promise((resolve, reject) => {
    handleExportWord({
      element: elementDom,
      fileName: filename,
      timeOut: 3000,
      callBack: (res) => {
        zip.file(`${filename}.docx`, res, { blob: true });
        resolve();
      },
      defultImg: "",
      // drawCanvas: [".img-box"],
    });
    loading.value = false;
  });
};

// 将string 转 dom
function stringToDom(htmlString) {
  const tempContainer = document.createElement("div");
  tempContainer.style.width = "100%";
  tempContainer.style.textAlign = "center";
  tempContainer.innerHTML = htmlString;
  return tempContainer;
}

const getPDFSize = (type) => {
  if (type == 7) {
    return [100, 150];
  } else if (type == 1 || type == 8 || type == 11) {
    return [100, 100];
  } else if (type == 10) {
    return [70, 30];
  } else {
    return [100, 20];
  }
};

const getImageData = (key) => {
  const imageData = image_list.get(key);
  if (imageData === undefined) {
    console.error(`Image data for key ${key} not found.`);
    return null;
  }
  return imageData;
};

const getTipIcon = (key) => {
  const imageData = tips_icon_map.get(key);
  if (imageData === undefined) {
    console.error(`Image data for key ${key} not found.`);
    return null;
  }
  return imageData;
};

const getBrandTipIcon = (key) => {
  const imageData = brand_tips_icon_map.get(key);
  if (imageData === undefined) {
    console.error(`Image data for key ${key} not found.`);
    return null;
  }
  return imageData;
};

const createCode = (row) => {
  // 生成唯一的 ID
  const uniqueId = `barcode_${row.sku}`;
  // 创建条形码元素
  const svgElement = document.createElement("svg");
  svgElement.id = uniqueId;
  // 获取容器元素
  const container = document.getElementById("barcode");
  // container.style.height = "110px";
  if (!container) {
    console.error(`Container with ID barcode not found`);
    return null;
  }
  container.innerHTML = "";
  // 将生成的 SVG 插入到指定的容器中
  container.appendChild(svgElement);
  try {
    // 调用 JsBarcode 生成条形码
    JsBarcode(`#${uniqueId}`, row.ean_number, {
      format: "ean13",
      width: 2.2,
      height: 50,
      // displayValue: true,
      fontSize: 15,
      marginTop: 10,
      marginLeft: 5,
    });
    const specification_model = document.createElement("div");
    specification_model.style.fontSize = "12px";
    specification_model.style.textAlign = "center";
    specification_model.textContent = row.specification_model;
    container.appendChild(specification_model);
  } catch (error) {
    console.error("Failed to generate barcode:", error);
    return null;
  }

  return container.outerHTML;
};
</script>
<style lang="scss" scoped>
.footer-btn {
  :deep(.el-button + .el-button) {
    margin-left: 8px !important;
  }
}
</style>
